<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :exclude-values="[ 'userCName','userCName1','groupCname', 'groupCname1']"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
      @reset="resetFunc"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startTime" label="流程开始时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTime"
            type="date"
            placeholder="流程开始时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="endTime" label="流程结束时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTime"
            type="date"
            placeholder="流程结束时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startId" label="流程发起人">
          <FIAutoInput
            v-model="state.query.userCName"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'fqr')"
            @change="changeEvent($event, 'fqr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="userId" label="经办人">
          <FIAutoInput
            v-model="state.query.userCName1"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'jbr')"
            @change="changeEvent($event, 'jbr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="deptId" label="经办部门">
          <!-- <FIAutoInput
            v-model="state.query.groupCname1"
            :options="deptList"
            value-key="groupCname"
            :displayKey="['groupEname', 'groupCname']"
            @select="selectDeptClick($event, 'jb_dept')"
            @change="changeEvent($event, 'jb_dept')"
          >
            <template #default="{ item }">
              <div>{{ item.groupEname }} {{ item.groupCname }}</div>
            </template>
          </FIAutoInput> -->
          <DeptTree v-model="state.query.deptId" />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="人员待办效率统计"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="deptCname"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
    >
      <template #headerBtn>
        <!-- <FIButton @click="menuShow = true" border style="margin-right:10px;">新增</FIButton> -->
        <!-- <el-button type="primary" @click="exportClick">导出</el-button> -->
        <FIButton id="export" border @click="exportClick"></FIButton>
      </template>
    </FITable>
    <FIModel v-model="proccessShow" title="经办查询列表" @close="proccessShow = false">
      <el-row :gutter="20">
        <el-col :span="6" class="flex-center">
          <FIFormItem label="经办人ID">
            <FIInput v-model="completerId" clearable disabled />
          </FIFormItem>
        </el-col>
        <el-col :span="6" class="flex-center">
          <FIFormItem label="经办人名称">
            <FIInput v-model="completerFullname" clearable disabled />
          </FIFormItem>
        </el-col>
        <el-col :span="6" class="flex-center">
          <FIFormItem label="经办人部门ID">
            <FIInput v-model="deptEname" clearable disabled />
          </FIFormItem>
        </el-col>
        <el-col :span="6" class="flex-center">
          <FIFormItem label="经办人部门名称">
            <FIInput v-model="deptCname" clearable disabled />
          </FIFormItem>
        </el-col>
      </el-row>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="detailList"
        :showSaveModel="false"
        :rowNo="true"
        v-model:columns="columns1"
        :insertable="false"
        :isLoading="isTableLoading2"
        :saveSuccessful="saveSuccessful"
        :settingConfig="settingConfig"
        :pageConfig="pageConfig1"
        @table-refresh="getList1"
        primaryKey="activityDefKey"
        @size-change="handleSizeChange1"
        @current-page-change="handleCurrentChange1"
      >
      </FITable>
      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <FIButton @click="proccessShow = false">关闭</FIButton>
          </div>
        </slot>
      </template>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import menuList from '../../user/authorityMaint/components/menuList'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiQueryPersonTask,
  apiExportFollow,
  apiQueryAllBpmCatogary,
  apiExportCount,
  apiQueryUser,
  apiQueryDept,
  apiQueryProccessActivity,
  apiQueryProccessPendTask,
} from '@/api/modules/EW.js'
import DeptTree from '../../components/DeptTree'
const route = useRoute()
const menuShow = ref(false)
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
const isTableLoading2 = ref(false)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const proccessShow = ref(false)
const detailList = ref([])
const processDefKey = ref('')
const completerId = ref('')
const state = reactive({
  query: {
    startTime: '',
    endTime: '',
    deptId: '',
    startDeptId: '',
    startId: '',
    userId: '',
    current: 1,
    size: 10,
    userCName: '',
    userCName1:'',
    groupCname: '',
    groupCname1: '',
  },
  dataList: [],
})
// const userId = ref('')
const completerFullname = ref('')
const deptCname = ref('')
const deptEname = ref('')
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const pageConfig1: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pagerCount: 3,
})
const columns1: Column[] = reactive([
  {
    label: '流程定义',
    prop: 'activityDefKey',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程名称',
    prop: 'activityName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '节点定义',
    prop: 'activityDefKey',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '节点名称',
    prop: 'activityName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人ID',
    prop: 'completerId',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人名称',
    prop: 'completerFullname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人部门ID',
    prop: 'deptEname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人部门名称',
    prop: 'deptCname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办任务数',
    prop: 'processTaskNum',
    align: 'center',
    sortable:true,
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '平均时长（小时）',
    prop: 'taskAvgDuration',
    sortable:true,
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])
const columns: Column[] = reactive([
  {
    label: '经办人ID',
    prop: 'completerId',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人名称',
    prop: 'completerFullname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人部门ID',
    prop: 'deptEname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人部门名称',
    prop: 'deptCname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办任务数',
    prop: 'processTaskNum',
    sortable:true,
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '平均时长（小时）',
    prop: 'taskAvgDuration',
    sortable:true,
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'detail', type: '' }],
  },
])

const checkedRows = ref([])
const userList = ref([])
const deptList = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  proccessShow.value = true
  completerId.value = rowData.completerId
  completerFullname.value = rowData.completerFullname
  deptCname.value = rowData.deptCname
  deptEname.value = rowData.deptEname
  getList1()
}
const handleCurrentChange1 = (e) => {
  pageConfig1.currentPage = e
  getList1()
}
const handleSizeChange1 = (e) => {
  pageConfig1.pageSize = e
  pageConfig1.currentPage = 1
  getList1()
}
const getList1 = () => {
  let par = {
    current: pageConfig1.currentPage,
    size: pageConfig1.pageSize || 10,
    startTime:state.query.startTime,
    endTime:state.query.endTime,
    startId:state.query.startId,
    startDeptId:state.query.startDeptId,
    completerId:state.query.userId,
    deptEname:deptEname.value
  }
  isTableLoading2.value = true
  apiQueryProccessPendTask(par)
    .then((res) => {
      if (res.data.success) {
        isTableLoading2.value = false
        detailList.value = res.data.data.result

        pageConfig1.pageSize = Number(res.data.data.size)
        pageConfig1.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {})
}
const resetFunc = () => {
  state.query.deptId = ''
  state.query.startDeptId = ''
  // state.query.userId = ''
  state.query.startId = ''
  // state.query.userCName = ''
  state.query.userId = ''
  state.query.groupCname = ''
  state.query.groupCname1 = ''
}
const changeEvent = (e, type) => {
  if (!e) {
    if (type == 'jb_dept') state.query.deptId = ''
    if (type == 'fq_dept') state.query.startDeptId = ''
    if (type == 'jbr') state.query.userId = ''
    if (type == 'fqr') state.query.startId = ''
  }
}
const selectClick = (data, type) => {
  console.log(data, type, 'data123')
  if (type == 'jbr') {
    state.query.userId = data.loginName
  } else {
    state.query.startId = data.loginName
  }
}

//导出
const exportClick = () => {
  apiExportCount(state.query)
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiQueryPersonTask(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // console.log(state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryDept = () => {
  apiQueryDept()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        deptList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
onMounted(() => {
  getQueryUser() //查询人员
  getQueryDept() //查询部门
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()//初始化不掉数据
})
</script>
<style lang="less" scoped></style>
